package a10_动态规划;

import java.util.Arrays;

/**
 * <p>
 * a16_目标和复习2
 * </p>
 *
 * @author flyduck
 * @since 2025/2/24
 */
public class a16_目标和复习2 {
    //leftSum + rightSum = sum
    //leftSum - rightSum = target
    //leftSum - (sum - leftSum) = target
    //leftSum = (target + sum)/2
    public int findTargetSumWays(int[] nums, int target) {
        int sum = Arrays.stream(nums).sum();
        if((sum + target) % 2 != 0){
            return 0;
        }

        int leftSum = Math.max((sum + target) / 2, sum - (sum + target) / 2);

        int[] dp = new int[leftSum + 1];
        dp[0] = 1;

        for (int i = 0; i < nums.length; i++) {
            for (int j = leftSum; j >= nums[i]; j--) {
                dp[j] = dp[j] + dp[j-nums[i]];
            }
        }

        return dp[leftSum];


    }
}
